<?php
/**
 * 活动模型
 * @author cjli
 *
 */
class ActivityModel extends Model
{

    public function _initialize()
    {
        parent::_initialize();
    }
    
	/**
	 * 根据当前时间 获取当前页面的活动
	 * @param int $nowtime 当前时间戳
	 * @return array;
	 */
	public static function getSeckill($nowtime)
	{
        $seckill_db = D('seckill');
        
        //正在秒杀活动的
        $where['_string']  = ' (start_time <= '.$nowtime.' and end_time >= '.$nowtime.')';
        $result = $seckill_db->where($where)->find();
        if($result){ return $result; }
        //第一个未开始的活动   -60秒为了让刚结束的活动 在页面显示60秒
        $where['_string']  = ' (end_time >= '.($nowtime - 60).')';
        $result = $seckill_db->where($where)->order('start_time asc')->find();
        if($result){ return $result; }
        //最后一个结束的活动
        $where['_string']  = ' (end_time <= '.$nowtime.')';
        $result = $seckill_db->where($where)->order('end_time desc')->find();
        if($result){ return $result; }
	}

	/**
	 * 返回时间格式
	 * @param int $time 时间秒数
	 * @return array;
	 */
	public static function getTime($time)
	{
		$result = array();
        $result['d'] = floor($time/3600/24);
        $result['h'] = floor(($time/3600)%24);
        $result['i'] = floor(($time/60)%60);
        $result['s'] = floor($time%60);
        return $result;
	}

    /**
     * 返回秒杀的URL
     * @param array $info 秒杀活动信息
     * @param int $tid 秒杀活动的子id
     * @return array;
     */
    public static function getSeckillURL($info, $tid)
    {
        $fid = $info['id'];
        $start_time =  $info['start_time'];
        $sign = MD5(C('seckill_key').$fid.$tid.$start_time);
        $url = U('activity/luckurl','fid='.$fid.'&tid='.$tid.'&sign='.$sign);
        return $url;
    }

    /**
     * 判断活动的商品是否被抢完，抢完立马结束
     * @param int $fid 秒杀活动的id
     */
    public static function isGameover($fid)
    {
        $qty = D('seckill_items')->where(array('fid'=>$fid))->getField('sum(qty)');
        $isget = D('seckill_result')->where(array('fid'=>$fid))->count(); 
        if($isget >= $qty){
            D('seckill')->where(array('id'=>$fid))->save(array('end_time'=>time()));
        }
    }

    /**
     * 添加一次分享情况
     * @param varchar $shareName 分享类型
     */
    public static function christmasAddShare($shareName)
    {
        global $user;
        $christmas_result_db = D('christmas_result');
        $where = array(
            'user_id' => $user['id'],
            'share'   => $shareName,
            );
        $id = $christmas_result_db->where($where)->getField('id');
        if(!$id){
           $add_data = array(
                'user_id' => $user['id'],
                'share'   => $shareName,
                'is_used' => 0,
           );
           return $id = $christmas_result_db->add($add_data);
        }
        return false;
    }
    /**
     * 统计下可抽奖的次数
     * @return int
     */
    public static function christmasShareCount($user_id)
    {
        $where = array(
            'user_id' => $user_id,
            'is_used' => 0,
            );
        $christmas_result_db = D('christmas_result');
        return $christmas_result_db->where($where)->count();
    }

    /**
     * 返回用户分享过的网站名称
     * @return array
     */
    public static function christmasShareName($user_id)
    {
        $where = array(
            'user_id' => $user_id,
        );
        $christmas_result_db = D('christmas_result');
        $shareres = $christmas_result_db->field('share')->where($where)->select();
        $reslist = array();
        foreach ($shareres as $key => $val) {
            $reslist[] = $val['share'];
        }
        return $reslist;
    }

     /**
     * 返回用户得奖情况
     * @param int $id 抽奖的id
     */
    public static function christmasLottery($user_id)
    {
        $christmas_result_db = D('christmas_result');
        $where = array(
            'user_id' => $user_id,
            'is_used' => 0,
        );
        $id = $christmas_result_db->where($where)->getField('id');
        if(!$id){
            return false;
        }
        $rand = C('christmas_prob');  //多少分之一的机会得超过$50红包的奖品
        
        $getRes = 1;
        if(rand(1,$rand) == rand(1,$rand)){
            $lotteryList = ActivityModel::christmasLotteryCount();
            foreach (array_reverse($lotteryList) as $val) {
                if($val['count'] < $val['num']){
                    if(rand(1, $val['prob']) == rand(1, $val['prob'])){
                        $getRes = $val['type'];break;
                    }                    
                }
            }
        }
      
        if($getRes==2 || $getRes==3  || $getRes==4){
            if($getRes==2){
                $prize_content = 'Christmas100';
                $returnMsg = L('christmas_bonus_100');
            }else if($getRes==3){
                $prize_content = 'Christmas150';
                $returnMsg = L('christmas_bonus_150');
            }else if($getRes==4){
                $prize_content = 'Christmas200';
                $returnMsg = L('christmas_bonus_200');
            }
            UserModel::user_bonus($prize_content,$user_id);//送红包
        }else if($getRes==5 || $getRes==6){
            if($getRes==5){
                $prize_content = self::addXmasInvite(60,'shirt');
                $returnMsg = str_replace('{$coupon_code}', $prize_content,L('christmas_coupon_60'));
            }else if($getRes==6){
                $prize_content = self::addXmasInvite(200,'suit');
                $returnMsg = str_replace('{$coupon_code}', $prize_content,L('christmas_coupon_200')); 
            }
        }else{
            $getRes = 1;
            $prize_content = 'Christmas50';
            $returnMsg = L('christmas_bonus_50');   
            UserModel::user_bonus($prize_content,$user_id);//送红包  
        }

       $get_data = array(
            'is_used'       => 1,
            'prize_type'    => $getRes,
            'prize_content' => $prize_content,
            'time'          => time(),
       );
       $christmas_result_db->where(array('id' => $id))->save($get_data); 
       return array('getRes'=>$getRes, 'returnMsg'=>$returnMsg, 'getId'=>$id);
    }
     /**
     * 生成优惠码
     * @param int $money 
     * @param int $typename      
     */    
    public static function addXmasInvite($money,$typename=''){
         //生成邀请人的优惠码
         $invite['coupon_code'] = 'Xmas'.$typename.substr(uniqid(),-6);
         $invite['coupon_money'] = $money;//优惠卷金额
         $invite['max_amount'] = 1000000;//使用优惠卷最大购物金额
         $invite['min_amount'] = $money;//使用优惠卷最小购物金额
         $invite['expiration_time'] = strtotime('2015-02-01 15:00:00');//优惠卷有效使用时间
         $invite['status'] = 2;
         $favorable_db = M('favorable'); 
         $user_coupon_id = $favorable_db->add($invite);
         return $invite['coupon_code'];
    }
     /**
     * 发送邮件
     * @param int $id 抽奖的id
     */
    public static function sendXmasEmail($email, $template, $titleOr=false, $titleRe=false, $contentOr=false, $contentRe=false, $langid=false){
        if($langid){
            $language_id = $langid;
        }else{
            global $language_id;
        }
        
         //发送邮件
        $mailInstance = new EmailModel();
        $email_template = UserModel::get_email_template_info($template, $language_id);
        if($email_template){
            if(!$titleOr || !$titleRe){
                $title    = $email_template['title'];
            }else{
                $title    = str_replace($titleOr, $titleRe, $email_template['title']);
            }
            if(!$contentOr || !$contentRe){
                $contents = $email_template['content'];
            }else{
                $contents = str_replace($contentOr,$contentRe,$email_template['content']);
            }
            $mailInstance->sendMail($email, $title, $contents);
        }
    }

     /**
     * 圣诞抽奖返回当天各奖项的送出数据
     * @param int $id 抽奖的id
     */
    public static function christmasLotteryCount()
    {  
        $christmas_result_db = D('christmas_result');

        $todaytime = strtotime(date('Y-m-d 00:00:00',time()));

        $where['_string'] = 'is_used=1 and time>='.$todaytime.' and prize_type>0';

        $christmas_result = $christmas_result_db->field('prize_type,count(*) as num')
                            ->where($where)->group('prize_type')->order('prize_type')->select();
        $resList = array();
        foreach (C('christmas_Lottery_num') as $key => $val) {
            $resList[$key]['type']  = $val['type'];
            $resList[$key]['num']  = $val['num'];
            $resList[$key]['prob'] = $val['prob'];
            $count = 0;
            foreach ($christmas_result as $k => $v) {
                if($v['prize_type'] == $val['type']){
                    $count = $v['num'];break;
                }
            }
            $resList[$key]['count'] = $count;
        }
        return $resList;

    }    


     /**
     * 判断是否抽奖
     * @param int $user_id 用户id
     */
    public static function fortunewheelLotteryCount($user_id)
    {  
        $fortunewheel_db = D('fortunewheel');
        $where['user_id'] = $user_id;
        $fortunewheel = $fortunewheel_db->where($where)->order('id desc')->find();
        return $fortunewheel;
    }  

     /**
     * 转盘抽奖
     * @param int $user_id 用户id
     */
    public static function fortunewheelLottery($user_id)
    {  
        $fortunewheel_db = D('fortunewheel');
        $where['user_id'] = $user_id;
        $fortunewheel = $fortunewheel_db->where($where)->find();
        if($fortunewheel){
            return false;
        }
        
        $getRes = 70;
        $rand = rand(1, 100);
        foreach (array_reverse(C('fortunewheel_Lottery_num')) as $val) {
            if($rand <= $val['prob']){
                $getRes = $val['prize_type'];break;
            }                 
        }

        $prize_content = 'BlackFriday'.$getRes;
        UserModel::user_bonus($prize_content,$user_id);//送红包  

        $get_data = array(
            'user_id'       => $user_id,
            'prize_type'    => $getRes,
            'prize_content' => $prize_content,
            'time'          => time(),
            'is_share'      => 0,
       );
       $fortunewheel_db->add($get_data); 

       return $get_data;
    }  

    /**
     * 转盘中奖列表
     * @param 
     */
    public static function fortunewheelList()
    {
        $fortunewheel_db = D('fortunewheel');
        $fortunewheel = $fortunewheel_db->field('user_id,prize_type')
                        ->where('display=1')->order('id desc')->limit('0, 15')->select();
        $returnRes = array();
        foreach ($fortunewheel as $key => $val) {
            $resOne = array();
            $userInfo = UserModel::get_user_info($val['user_id']);
            if($userInfo){
                $emailArr = explode('@', $userInfo['email']);
                $strlen = strlen($emailArr[0]);;
                if($strlen>3){
                   $emailstr = substr($emailArr[0] , 0 ,-3).'***@'.$emailArr[1];
                }else{
                   $emailstr = substr($emailArr[0] , 0 ,-1).'*&'.$emailArr[1];
                }
                $resOne['email'] = $emailstr;
                $resOne['prize_type'] = $val['prize_type'];               
            }
            $returnRes[] = $resOne;
        }
        return $returnRes;
    }

    /**
     * 转盘分享类型处理
     * @param varchar $shareName 分享类型
     */
    public static function fortunewheelAddShare($user_id)
    {
        $fortunewheel_db = D('fortunewheel');
        $where['user_id'] = $user_id;
        $fortunewheel = $fortunewheel_db->where($where)->save(array('is_share'=>1));
    }

    /**
     * 转轮中奖后没有分享，超过一天
     */
    public static function sendEmailA() 
    {   
        $fortunewheel_db = D('fortunewheel');
        $where = array(
            'is_share' => 0,
            'is_send_mail' => 0,
        );
        $aborttime = time()-3600*24;
        $where['_string'] = 'time<'.$aborttime.'';
        $resultRes = $fortunewheel_db->field('id')->where($where)->order('id asc')->limit('0, 30')->select();

        foreach($resultRes as $key=>$val){
            $where = array(
                'id' => $val['id'],
            );
            $fortunewheel_db->where($where)->save(array('is_send_mail'=>1));
            $url = 'http://'.$_SERVER['HTTP_HOST'].'/special/sendEmailA';
            EmailModel::Asynchronous_request($url, array('id'=>$val['id']) , 'post');
        }

        $result = $fortunewheel_db->where($where)->count();
        if($result>0){
            sleep(1);
            self::sendEmailA();
        }else{
            return true;
        }
    }

     /**
     * 红包过期前3天（12月6日）
     */
    public static function sendEmailB() 
    {   
        $fortunewheel_db = D('fortunewheel as f');
        $where['_string'] = 'ub.used_time=0';

        $resultRes = $fortunewheel_db->join('bonus_type as b on(b.type_name=f.prize_content)')
                    ->join('user_bonus as ub on(ub.user_id=f.user_id and ub.bonus_id=b.id)')
                    ->field('f.id')->where($where)->group('f.id ')->order('f.id asc')->select();

        foreach($resultRes as $key=>$val){
            $url = 'http://'.$_SERVER['HTTP_HOST'].'/special/sendEmailB';
            EmailModel::Asynchronous_request($url, array('id'=>$val['id']) , 'post');
        }
        
        return true;
    }   
}